/**
 * 
 */
package com.jxc.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.jxc.dao.RepertoryDaoI;
import com.jxc.model.po.Repertory;
import com.jxc.model.vo.VRepertory;

/**
 * @author Tino
 * 
 */
@Repository("repertoryDao")
public class RepertoryDaoImpl implements RepertoryDaoI {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public List<VRepertory> list(VRepertory vrepertory) {
		Session session = this.sessionFactory.openSession();
		String hql = "from Repertory t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vrepertory, hql, values);

		Query q = session.createQuery(hql);
		if (values != null && values.size() > 0) {
			for (int i = 0; i < values.size(); i++) {
				q.setParameter(i, values.get(i));
			}
		}
		
		List<VRepertory> list = this.changeModelRepertory(q.list());
		session.close();
		return list;
	}

	private List<VRepertory> changeModelRepertory(List<Repertory> repertories) {
		List<VRepertory> vrepertories = new ArrayList<VRepertory>();
		if (repertories != null && repertories.size() > 0) {
			for (Repertory repertory : repertories) {
				VRepertory vrepertory = new VRepertory();
				BeanUtils.copyProperties(repertory, vrepertory);
				vrepertory.setUid(repertory.getUser().getId());
				vrepertory.setUname(repertory.getUser().getUsername());
				vrepertories.add(vrepertory);
			}
		}
		return vrepertories;
	}

	private String addWhere(VRepertory vrepertory, String hql, List<Object> values) {
		if (vrepertory.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vrepertory.getId());
		}
		if (vrepertory.getUid() != null) {
			hql += " and t.user.id = ? ";
			values.add(vrepertory.getUid());
		}
		if (vrepertory.getName() != null && !vrepertory.getName().trim().equals("")) {
			hql += " and t.name like ? ";
			values.add("%%" + vrepertory.getName().trim() + "%%");
		}
		return hql;
	}
}
